package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.GoodsCategory;
import com.example.demo.mapper.GoodsCategoryMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

@RestController
@RequestMapping("/goods-category")
public class GoodsCategoryController extends BaseController {

    @Resource
    GoodsCategoryMapper goodsCategoryMapper;

    @PostMapping
    public Result<?> save(@RequestBody GoodsCategory goodsCategory) {
        goodsCategory.setCreateTime(new Date());
        return Result.success(goodsCategoryMapper.insert(goodsCategory));
    }

    @PutMapping
    public Result<?> update(@RequestBody GoodsCategory goodsCategory) {
        return Result.success(goodsCategoryMapper.updateById(goodsCategory));
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        return Result.success(goodsCategoryMapper.deleteById(id));
    }

    @GetMapping("/{id}")
    public Result<?> getById(@PathVariable Long id) {
        return Result.success(goodsCategoryMapper.selectById(id));
    }

    @GetMapping("/all")
    public Result<?> findAll(@RequestParam(defaultValue = "0") Integer isVisible) {
        QueryWrapper<GoodsCategory> queryWrapper = new QueryWrapper<>();
        if (isVisible != 0) {
            queryWrapper.eq("is_visible", 1);
        }
        return Result.success(goodsCategoryMapper.selectList(queryWrapper));
    }

    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "0") Integer isVisible) {
        QueryWrapper<GoodsCategory> queryWrapper = new QueryWrapper<>();
        if (isVisible != 0) {
            queryWrapper.eq("is_visible", 1);
        }
        Page<GoodsCategory> page = goodsCategoryMapper.selectPage(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }

}
